from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from .forms import UserLoginForm


def user_login(request):
    if request.method == 'POST':
        user_login_form = UserLoginForm(request.POST)
        # 判断表单数据是否完整
        if user_login_form.is_valid():
            # 获取表单数据
            data = user_login_form.cleaned_data
            user = authenticate(username=data['username'], password=data['password'])
            if user:
                # django自带的登录方式，登录信息保存在session中
                login(request, user)
                return redirect(reverse('article:index'))
            else:
                context = {
                    'msg': '账号或密码错误'
                }
                return render(request, 'login.html', context)
        else:
            context = {
                'msg': '请输入完整的信息'
            }
            return render(request, 'login.html', context)
    else:
        user_login_form = UserLoginForm()
        context = {
            'form': user_login_form
        }
        return render(request, 'login.html', context)


@login_required(login_url='bloguser:user_login')
def user_center(request):
    return render(request, 'per_center.html')


# 退出
def user_logout(request):
    logout(request)
    request.session.flush()
    return redirect(reverse("article:index"))


def user_register(request):
    if request.method == "POST":
        return HttpResponse("尚未开通注册功能，请期待")
    else:
        return render(request, 'register.html')
